<?php

namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;

class Product extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'product';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    protected $append = [
        'node_count',
        'node_detail_count',
        'quote_count',
        'first_parent_id'
    ];

    // 获取节点数
    public function getNodeCountAttr($value, $data)
    {
        return Node::where('product_id', $data['id'])->count();
    }

    // 获取数据量
    public function getNodeDetailCountAttr($value, $data)
    {
        $count1 = NodeDetail::where('product_id', $data['id'])->count();
        $count2 = Node::where('product_id', $data['id'])->where('is_factor', 1)->count();
        return $count1 + $count2;
    }

    // 获取引用量
    public function getQuoteCountAttr($value, $data)
    {
        return Node::where('product_id', $data['id'])->where('is_factor', 1)->count();
    }

    // 获取最后编辑时间
    public function getLastEditTimeAttr($value, $data)
    {
        $max1 = Node::where('product_id', $data['id'])->max('updatetime');
        $max2 = NodeDetail::where('product_id', $data['id'])->max('updatetime');
        $updatetime = $this->getData('updatetime');
        $times = [$max1, $max2,$updatetime ?: 0];
        $time = max($times);
//        return time() - $time > 7 * 86400 ? date("Y-m-d H:i:s", $time) : human_date($time);
        return date("Y-m-d H:i:s", $time);
    }


    // 获取删除时间
    public function getDeleteDateTimeAttr($value, $data)
    {

        if (isset($data['deletetime']) && $data['deletetime']) {
            $time = $data['deletetime'];
            return time() - $time > 7 * 86400 ? date("n月d日", $time) : human_date($time);
        }
        return '';
    }

    // 获取产品最父级节点id
    public function getFirstParentIdAttr($value, $data)
    {
        return Node::where('product_id', $data['id'])->where('pid', 0)->value('id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

}
